import React, { Component } from 'react'
import { Button } from "antd";

export default class index extends Component {
    constructor(props) {
        super();        
        this.state = {
            name:"柴正盼",
            age: 12,
            
        }
    }

    changeAge = () => {
        this.setState({
            age:this.state.age+1
        });
    }

    // 比较两个对象的内容是否一样。
    compareObj(obj1,obj2){
        
        if(typeof obj1!="object" || typeof obj2!="object" ){
            return false;
        }
        let keys1 = Object.keys(obj1);
        let keys2 = Object.keys(obj2);
        let maxObj = obj2;
        if(keys1.length>keys2.length){
            maxObj = obj1;
        }

        for(let key in maxObj){
            if(typeof obj1[key]=="object" && typeof obj2[key]=="object"){//属性依然是引用类型
                if(!this.compareObj(obj1[key],obj2[key])){
                    return false;
                }
            }else{
                // 属性是基本类型
                if(obj1[key]!=obj2[key]){
                    return false;
                }
            }            
        }

        return true;

    }


    // 组件应该更新吗？
    shouldComponentUpdate(nextProps, nextState) {
        console.log("shouldComponentUpdate");
        console.log("this.state",this.state);
        console.log("nextState", nextState);
        // if(新旧值一样){

        if(this.compareObj(this.state,nextState)){
            return false;
        }
        return true;
    }

    render() {
        console.log("render");
        return (
            <>
                <h2>性能优化</h2>
                <p>年龄：{this.state.age}</p>
                <Button type="primary" onClick={this.changeAge}>修改年龄</Button>
            </>
        )
    }
}
